package oa.hleast.common.utils;

import cn.hutool.core.date.DateUtil;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 时间相关工具类
 */
public class DateUtils extends DateUtil {
    /**
     * JDK8获取一段时间范围内符合星期几的日期集合
     *
     * @param startDate    开始时间
     * @param endDate      结束时间
     * @param workDateList 周几 [1,2,3,4]
     */
    public static List<LocalDate> getMeetDayOfWeekLocalDates(LocalDate startDate, LocalDate endDate, List<Integer> workDateList) {

        List<DayOfWeek> dayOfWeeks = workDateList.stream()
                .map(DayOfWeek::of)
                .collect(Collectors.toList());

        long distance = ChronoUnit.DAYS.between(startDate, endDate);

        return Stream.iterate(startDate, d -> d.plusDays(1))
                .limit(distance + 1)
                .filter(localDate -> dayOfWeeks.contains(localDate.getDayOfWeek()))
                .collect(Collectors.toList());
    }

    /**
     * JDK8获取一段时间范围内符合星期几的日期集合
     *
     * @param startDate    开始时间
     * @param endDate      结束时间
     * @param workDateList 周几 [1,2,3,4]
     */
    public static List<Date> getMeetDayOfWeekDates(Date startDate, Date endDate, List<Integer> workDateList) {
        LocalDate start = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate end = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        List<LocalDate> meetDayOfWeekLocalDates = getMeetDayOfWeekLocalDates(start, end, workDateList);
        return meetDayOfWeekLocalDates.stream()
                .map(localDate -> Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()))
                .collect(Collectors.toList());
    }

    public static Date createCalendar(int year, int month, int day, int hour, int minute, int second) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, day);
        //时
        cal.set(Calendar.HOUR_OF_DAY, hour);
        //分
        cal.set(Calendar.MINUTE, minute);
        //秒
        cal.set(Calendar.SECOND, second);
        return cal.getTime();
    }

}
